import { Room, RoomState } from "./Room";
import { arr_hallPlayer, createRoom, map_room, numOfHallPlayers, sendObj, VERSION } from "./WebSocket";

export class Player{

    timer:number;

    constructor(id:number,connection:any){
        this.id = id;
        this.connection = connection;
        this.timer = setInterval(()=>{
            this.heartbeat()
        },1000);
    }

    

    id:number;
    connection:any;
    roomId:number = -1;      //房间号

    /**
     * 开启匹配
     */
    matching(obj:any){
        //找房间加入
        for(let room of map_room.values()){
            if(room.state == RoomState.OPEN && room.type == obj.type && room.arr_players.length < room.type){               
                room.addPlayer(this)
                return
            }
        }
        //没找到房间就自己创建一个
        const room = createRoom(obj.type)
        map_room.set(room.id,room);
        room.addPlayer(this)
    }

    /**
     * 取消匹配
     */
    cancel(){
        map_room.get(this.roomId).reducePlayer(this);
    }

    /**
     * 匹配成功
     */
    success(){
        arr_hallPlayer.delete(this);
        numOfHallPlayers();
    }

    /**
     * 玩家掉线
     */
    dropLine(){        
        clearInterval(this.timer)
        if(this.roomId!=-1){
            map_room.get(this.roomId)?.dropLine(this);
        }
    }

    /**
     * 检查版本号
     */
    checkVersion(version: string){
        sendObj(this.connection,{other:"check_version","result":version == VERSION})
    }

    /**
     * 心跳检测
     */
    heartbeat(){
        sendObj(this.connection,{other:"heartbeat"})
    }
}